package com.example.order.metrics;

import com.example.order.service.ActiveOrderManager;
import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.Gauge;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.Timer;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Supplier;

/**
 * 业务指标工具类，统一管理所有自定义监控指标
 */
@Component
public class BusinessMetrics {
    // 订单状态计数器
    private final Map<String, Counter> orderStatusCounters = new ConcurrentHashMap<>();
    // 支付方式计数器
    private final Map<String, Counter> paymentMethodCounters = new ConcurrentHashMap<>();
    // 订单金额总和计数器
    private final Counter orderAmountTotal;
    // 支付处理时间计时器
    private final Timer paymentProcessingTimer;
    // MeterRegistry实例
    private final MeterRegistry registry;

    public BusinessMetrics(MeterRegistry registry, ActiveOrderManager activeOrderManager) {
        this.registry = registry;
        
        // 初始化订单总金额计数器
        this.orderAmountTotal = Counter.builder("business.order.amount.total")
                .description("订单总金额")
                .register(registry);
        
        // 初始化支付处理时间计时器
        this.paymentProcessingTimer = Timer.builder("business.order.payment.processing.time")
                .description("订单支付处理耗时")
                .register(registry);
        
        // 初始化活跃订单数量Gauge
        Gauge.builder("business.order.active.count", activeOrderManager::getActiveOrderCount)
                .description("当前活跃订单数量")
                .register(registry);
    }

    /**
     * 记录订单状态
     */
    public void incrementOrderStatus(String status) {
        Counter counter = orderStatusCounters.computeIfAbsent(status, s -> 
            Counter.builder("business.order.status.total")
                    .tag("status", s)
                    .description("按状态统计的订单数量")
                    .register(registry)
        );
        counter.increment();
    }

    /**
     * 记录支付方式
     */
    public void incrementPaymentMethod(String method) {
        Counter counter = paymentMethodCounters.computeIfAbsent(method, m ->
            Counter.builder("business.order.payment.method")
                    .tag("method", m)
                    .description("按支付方式统计的订单数量")
                    .register(registry)
        );
        counter.increment();
    }

    /**
     * 累加订单金额
     */
    public void addOrderAmount(BigDecimal amount) {
        orderAmountTotal.increment(amount.doubleValue());
    }

    /**
     * 记录支付处理时间
     */
    public void recordPaymentProcessingTime(long seconds) {
        paymentProcessingTimer.record(seconds, java.util.concurrent.TimeUnit.SECONDS);
    }
}
